<template>
  <div class="server-edit p-4">
    <el-card class="box-card">
      <template #header>
        <div class="card-header flex items-center justify-between">
          <h2 class="text-xl font-bold">编辑服务器</h2>
          <el-button @click="goBack">返回</el-button>
        </div>
      </template>

      <div v-loading="loading">
        <div v-if="formData" class="max-w-3xl">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="基本信息" name="basic">
              <el-form
                ref="formRef"
                :model="formData"
                :rules="formRules"
                label-width="100px"
              >
                <el-form-item label="IP地址" prop="ip">
                  <el-input v-model="formData.ip" placeholder="请输入IP地址" />
                </el-form-item>

                <el-form-item label="主机名" prop="hostname">
                  <el-input v-model="formData.hostname" placeholder="请输入主机名" />
                </el-form-item>

                <el-form-item label="产品线" prop="product_line">
                  <el-input v-model="formData.product_line" placeholder="请输入产品线" />
                </el-form-item>

                <el-form-item label="服务器类型" prop="server_type">
                  <el-select v-model="formData.server_type" placeholder="请选择服务器类型" class="w-full">
                    <el-option label="Web服务器" :value="ServerType.WEB" />
                    <el-option label="数据库服务器" :value="ServerType.DATABASE" />
                    <el-option label="应用服务器" :value="ServerType.APPLICATION" />
                    <el-option label="文件服务器" :value="ServerType.FILE" />
                    <el-option label="缓存服务器" :value="ServerType.CACHE" />
                    <el-option label="代理服务器" :value="ServerType.PROXY" />
                    <el-option label="其他" :value="ServerType.OTHER" />
                  </el-select>
                </el-form-item>

                <el-form-item label="服务器状态" prop="server_status">
                  <el-select v-model="formData.server_status" placeholder="请选择服务器状态" class="w-full">
                    <el-option label="在线" :value="ServerStatus.ONLINE" />
                    <el-option label="离线" :value="ServerStatus.OFFLINE" />
                    <el-option label="维护中" :value="ServerStatus.MAINTENANCE" />
                    <el-option label="已退役" :value="ServerStatus.DECOMMISSIONED" />
                  </el-select>
                </el-form-item>

                <el-form-item label="使用状态" prop="usage_status">
                  <el-select v-model="formData.usage_status" placeholder="请选择使用状态" class="w-full">
                    <el-option label="使用中" :value="ServerUsageStatus.IN_USE" />
                    <el-option label="可用" :value="ServerUsageStatus.AVAILABLE" />
                    <el-option label="已预留" :value="ServerUsageStatus.RESERVED" />
                    <el-option label="已报废" :value="ServerUsageStatus.RETIRED" />
                  </el-select>
                </el-form-item>

                <el-form-item label="环境" prop="environment">
                  <el-select v-model="formData.environment" placeholder="请选择服务器环境" class="w-full">
                    <el-option label="测试环境" :value="ServerEnvironment.TESTING" />
                    <el-option label="开发环境" :value="ServerEnvironment.DEVELOPMENT" />
                    <el-option label="线上环境" :value="ServerEnvironment.PRODUCTION" />
                  </el-select>
                </el-form-item>

                <el-form-item label="序列号" prop="sn">
                  <el-input v-model="formData.sn" placeholder="请输入序列号（可选）" />
                </el-form-item>

                <el-form-item label="机柜位置" prop="rack_location">
                  <el-input v-model="formData.rack_location" placeholder="请输入机柜位置（可选）" />
                </el-form-item>
                
                <!-- 将购买日期移到可编辑表单中 -->
                <el-form-item label="购买日期" prop="purchase_date">
                  <el-date-picker
                    v-model="formData.purchase_date"
                    type="date"
                    placeholder="请选择购买日期"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>

                <el-form-item label="备注" prop="notes">
                  <el-input
                    v-model="formData.notes"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入备注（可选）"
                  />
                </el-form-item>
                
                <!-- 按钮移到可编辑表单最后面 -->
                <el-form-item>
                  <el-button type="primary" @click="submitForm" :loading="saving">提交</el-button>
                  <el-button @click="resetForm">重置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            
            <el-tab-pane label="物理配置信息" name="physical" v-if="hasPhysicalInfo">
              <div class="mt-4">
                <div class="text-sm text-gray-500 mb-4">
                  <el-alert
                    title="物理配置信息由系统自动收集，仅供查看"
                    type="info"
                    :closable="false"
                  />
                </div>
                <el-descriptions :column="2" border>
                  <el-descriptions-item label="CPU型号">{{ formData.cpu_model || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="CPU核心数">{{ formData.cpu_cores ? `${formData.cpu_cores}核` : '-' }}</el-descriptions-item>
                  <el-descriptions-item label="CPU线程数">{{ formData.cpu_threads ? `${formData.cpu_threads}线程` : '-' }}</el-descriptions-item>
                  <el-descriptions-item label="内存大小">{{ formData.memory_size ? `${formData.memory_size}GB` : '-' }}</el-descriptions-item>
                  <el-descriptions-item label="磁盘大小">{{ formData.disk_size ? `${formData.disk_size}GB` : '-' }}</el-descriptions-item>
                  <el-descriptions-item label="系统版本">{{ formData.system_version || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="内核版本">{{ formData.kernel_version || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="运行时长">{{ formData.uptime ? `${formatUptime(formData.uptime)}` : '-' }}</el-descriptions-item>
                  <el-descriptions-item label="磁盘详情" :span="2">
                    <pre v-if="formData.disk_info" class="whitespace-pre-wrap text-sm">{{ formatDiskInfo(formData.disk_info) }}</pre>
                    <span v-else>-</span>
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="ServerEdit">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { getServer, updateServer } from '@/request/server-api'
import { ServerType, ServerStatus, ServerUsageStatus, ServerEnvironment, type Server, type ServerUpdateRequest } from '@/model/server-model'
import dayjs from 'dayjs'

// 路由对象
const router = useRouter()
const route = useRoute()

// 表单引用
const formRef = ref<FormInstance>()

// 服务器ID
const serverId = ref(Number(route.params.id) || 0)

// 加载状态
const loading = ref(false)
const saving = ref(false)

// 当前激活的标签页
const activeTab = ref('basic')

// 表单数据
const formData = ref<ServerUpdateRequest>({
  id: 0,
  ip: '',
  hostname: '',
  product_line: '',
  server_type: ServerType.WEB,
  server_status: ServerStatus.ONLINE,
  usage_status: ServerUsageStatus.AVAILABLE,
  environment: undefined,
  sn: '',
  rack_location: '',
  notes: ''
})

// 表单验证规则
const formRules = reactive<FormRules>({
  ip: [
    { required: true, message: '请输入IP地址', trigger: 'blur' },
    { pattern: /^(\d{1,3}\.){3}\d{1,3}$/, message: 'IP地址格式不正确', trigger: 'blur' }
  ],
  hostname: [
    { required: true, message: '请输入主机名', trigger: 'blur' },
    { min: 2, max: 50, message: '主机名长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  server_type: [
    { required: true, message: '请选择服务器类型', trigger: 'change' }
  ],
  server_status: [
    { required: true, message: '请选择服务器状态', trigger: 'change' }
  ],
  usage_status: [
    { required: true, message: '请选择使用状态', trigger: 'change' }
  ]
})

/**
 * 获取服务器详情
 */
const getServerDetail = async () => {
  if (!serverId.value) {
    ElMessage.error('服务器ID无效')
    goBack()
    return
  }

  loading.value = true
  try {
    const response = await getServer(serverId.value)
    if (response.code === 0) {
      // 将获取的数据填充到表单中
      const serverData: Server = response.data
      formData.value = {
        id: serverData.id,
        ip: serverData.ip,
        hostname: serverData.hostname,
        product_line: serverData.product_line,
        server_type: serverData.server_type,
        server_status: serverData.server_status,
        usage_status: serverData.usage_status,
        environment: serverData.environment,
        sn: serverData.sn,
        rack_location: serverData.rack_location,
        notes: serverData.notes,
        // 物理配置信息
        cpu_model: serverData.cpu_model,
        cpu_cores: serverData.cpu_cores,
        cpu_threads: serverData.cpu_threads,
        memory_size: serverData.memory_size,
        disk_size: serverData.disk_size,
        disk_info: serverData.disk_info,
        system_version: serverData.system_version,
        kernel_version: serverData.kernel_version,
        // 时间信息
        uptime: serverData.uptime,
        purchase_date: serverData.purchase_date
      }
    } else {
      ElMessage.error(response.errorMsg || '获取服务器详情失败')
      goBack()
    }
  } catch (error) {
    console.error('获取服务器详情失败:', error)
    ElMessage.error('获取服务器详情失败')
    goBack()
  } finally {
    loading.value = false
  }
}

/**
 * 提交表单
 */
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('请正确填写表单信息')
      return
    }
    
    saving.value = true
    try {
      if (!formData.value || !serverId.value) {
        ElMessage.error('服务器数据无效')
        return
      }
      
      const response = await updateServer(serverId.value, formData.value)
      
      if (response.code === 0) {
        ElMessage.success('更新服务器成功')
        router.push(`/server/detail/${serverId.value}`)
      } else {
        ElMessage.error(response.errorMsg || '更新服务器失败')
      }
    } catch (error) {
      console.error('更新服务器失败:', error)
      ElMessage.error('更新服务器失败')
    } finally {
      saving.value = false
    }
  })
}

/**
 * 重置表单
 */
const resetForm = () => {
  getServerDetail()
}

/**
 * 返回详情页
 */
const goBack = () => {
  if (serverId.value) {
    router.push(`/server/detail/${serverId.value}`)
  } else {
    router.push('/server/list')
  }
}

/**
 * 检查是否存在物理信息
 */
const hasPhysicalInfo = computed(() => {
  if (!formData.value) return false
  
  return !!(
    formData.value.cpu_model ||
    formData.value.cpu_cores ||
    formData.value.cpu_threads ||
    formData.value.memory_size ||
    formData.value.disk_size ||
    formData.value.disk_info ||
    formData.value.system_version ||
    formData.value.kernel_version ||
    formData.value.uptime ||
    formData.value.purchase_date
  )
})

/**
 * 格式化运行时间
 * @param hours 运行时间（小时）
 * @returns 格式化后的运行时间（天+小时）
 */
const formatUptime = (hours: number) => {
  const days = Math.floor(hours / 24)
  const remainingHours = Math.round((hours % 24) * 10) / 10
  
  if (days > 0) {
    return `${days}天 ${remainingHours}小时`
  } else {
    return `${remainingHours}小时`
  }
}

/**
 * 格式化日期
 * @param dateString 日期字符串
 * @returns 格式化后的日期字符串
 */
const formatDate = (dateString: string) => {
  return dayjs(dateString).format('YYYY-MM-DD')
}

/**
 * 格式化磁盘信息JSON
 * @param diskInfo 磁盘信息JSON字符串
 * @returns 格式化后的磁盘信息
 */
const formatDiskInfo = (diskInfo: string) => {
  try {
    // 尝试解析JSON
    const diskData = JSON.parse(diskInfo)
    // 使用JSON.stringify格式化显示，使用缩进增加可读性
    return JSON.stringify(diskData, null, 2)
  } catch (e) {
    // 如果解析失败，返回原始字符串
    return diskInfo
  }
}

onMounted(() => {
  getServerDetail()
})
</script>
